import create from "zustand";
import { devtools, persist } from "zustand/middleware";

import { createClient } from "~/modules/api-server/http-client";
import { loadAppConfig } from "~/modules/shared/app-config";
import { STORAGE_NAMES } from "~/modules/storage/storage-names";

const initState = (): ApiState => {
  return {
    client: undefined,
  };
};
export const useApiStore = create<ApiState & ApiActions>(
  // @ts-ignore
  devtools(
    persist(
      (set, get, api) => ({
        ...initState(),
        createApi: () => {
          set({ client: useApiService() });
        },
      }),
      {
        name: STORAGE_NAMES.RESTAPI.name,
        version: STORAGE_NAMES.RESTAPI.version,
      }
    )
  )
);

export interface ApiState {
  client: any;
}

export interface ApiActions {
  createApi: () => void;
}

export const useApiService = () => {
  const appConfig = loadAppConfig();
  const { client } = createClient({
    url: appConfig.apiServer.url_custom_param_test,
  });
  return client;
};

export const useApi = () => {
  let { client, createApi } = useApiStore();
  if (!client) {
    createApi();
    client = useApiStore().client;
  }

  return client;
};
